// src/main/java/com/fjnu/dao/impl/CommentDaoImpl.java
package com.fjnu.dao.impl;

import com.fjnu.dao.CommentDao;
import com.fjnu.entity.Comment;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.Date;
import java.util.List;

public class CommentDaoImpl implements CommentDao {
    private JdbcTemplate jdbcTemplate;
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    @Override
    public int insert(Comment newComment) {
        if (newComment.getArticleId() == null) {
            return 0;
        }
        String sql = "INSERT INTO tb_comment(content, article_id, user_id, support, oppose, create_time, update_time) " +
                "VALUES(?, ?, ?, ?, ?, ?, ?)";
        return jdbcTemplate.update(sql, newComment.getContent(), newComment.getArticleId(),
                newComment.getUserId(), newComment.getSupport(), newComment.getOppose(),
                newComment.getCreateTime(), newComment.getUpdateTime());
    }
    @Override
    public int updateSupport(Integer commentId, Integer incremented) {
        String sql = "UPDATE tb_comment SET support = support + ?, update_time = ? WHERE id = ?";
        return jdbcTemplate.update(sql, incremented, new Date(), commentId);
    }

    @Override
    public int updateOppose(Integer commentId, Integer incremented) {
        String sql = "UPDATE tb_comment SET oppose = oppose + ?, update_time = ? WHERE id = ?";
        return jdbcTemplate.update(sql, incremented, new Date(), commentId);
    }

    @Override
    public List<Comment> selectAllCommentsForArticle(Integer articleId) {
        if (articleId == null) {
            return null;
        }
        String sql = "SELECT * FROM tb_comment WHERE article_id = ? ORDER BY create_time DESC";
        try {
            return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Comment.class), articleId);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public List<Comment> selectCommentsWithLimitForArticle(Integer articleId, Integer startIndex, Integer endIndex) {
        List<Comment> allComments = selectAllCommentsForArticle(articleId);
        if (allComments == null || allComments.isEmpty()) {
            return null;
        }

        int fromIndex = Math.min(startIndex, allComments.size());
        int toIndex = Math.min(endIndex, allComments.size());

        if (fromIndex >= toIndex) {
            return null;
        }

        return allComments.subList(fromIndex, toIndex);
    }
}